<template>
    <el-drawer
        title="JsonSchemaEditor"
        :visible.sync="visible"
        append-to-body
        size="90%"
        direction="btt">
        <div slot="title">
            <span>JsonSchemaEditor</span>
            <span style="float: right">
                <i class="el-icon-s-tools" v-if="setting" @click="setting=!setting"/>
                <i class="el-icon-setting" v-else @click="setting=!setting"/>&nbsp;
                <i class="el-icon-arrow-down" v-if="show" @click="show=!show"/>
                <i class="el-icon-arrow-right" v-else @click="show=!show"/>&nbsp;
            </span>
        </div>
        <div class="jse">
            <div>
                <div v-if="setting">
                    <div style="display: flex">
                        <el-alert
                            title="编辑器系统配置，涉及类型处理和相关属性功能，请谨慎操作！"
                            :closable="false" type="warning" effect="dark"/>
                        <el-button type="danger" @click="flush" style="height: 37px">保存</el-button>
                    </div>
                    <el-tabs type="card" editable @tab-click="settingSys">
                        <el-tab-pane
                            :key="index"
                            v-for="(item, index) in JsonSchema.SCHEMA_KEYS"
                            :label="index"
                            :name="index"
                        >
                        </el-tab-pane>
                    </el-tabs>
                </div>
                <Collapse>
                    <el-card id="jsonStr" v-if="show">
                        <div>
                            <el-button size="mini" type="primary" @click="flush">重置</el-button>
                            <el-button size="mini" type="primary" @click="load">刷新</el-button>
                            <el-tag effect="dark" size="small" style="float: right; margin: 0 0 10px"
                                    type="success">
                                设置
                            </el-tag>
                        </div>
                        <div style="margin-top: 15px">
                            <el-input ref="input" v-model="jsonStr" :autosize="{minRows: 2, maxRows: 10}"
                                      type="textarea" @blur="flushJson" @focus="writeJson" :disabled="onlyRead"
                                      @keydown.tab.native="tabInput($event)"/>
                        </div>
                    </el-card>
                </Collapse>
                <el-card style="margin-top: 5px">
                    <div :style="{maxHeight : `calc(100vh - ${otherHeight}`}" class="edit">
                        <JsonSchemaTable :schema="schema" @updateTable="updateSchema" ref="table"/>
                    </div>
                </el-card>
            </div>
        </div>
    </el-drawer>
</template>

<script>

import Collapse from 'element-ui/lib/transitions/collapse-transition';
import {infoNotify, JsonSchema} from "@/view/JsonSchema";

export default {
    components: {
        JsonSchemaTable: () => import('@/view/JsonSchemaTable.vue'),
        Collapse,
    },
    computed: {
        JsonSchema() {
            return JsonSchema
        }
    },
    data() {
        return {
            visible: false,
            show: true,
            setting: false,
            onlyRead: false,
            loadFalg: false,
            schemaKey: '1222',
            // schema 对象
            jsonStr: '',
            schema: {},
            schema2: {
                type: 'object',
                title: 'title',
                properties: {
                    field_1: {
                        type: 'string',
                    },
                },
            },
            otherHeight: '290px',
        };
    },
    watch: {
        schema() {
            this.jsonStr = JSON.stringify(this.schema, JsonSchema.replacer, 4)
        }
    },
    mounted() {
        this.schema = {
            "type": "object",
            "title": "title",
            "description": "这是个人",
            "required": [
                "hobby",
                "name"
            ],
            "properties": {
                "hobby": {
                    "type": "array",
                    "description": "兴趣列表",
                    "items": {
                        "type": "string",
                        "default": "[打篮球，唱跳RAP]",
                        "description": "兴趣爱好"
                    }
                },
                "name": {
                    "type": "string",
                    "default": "坤哥",
                    "description": "姓名",
                    "enumDesc": "我只会心疼哥哥",
                    "enum": [
                        "坤哥",
                        "吉哥",
                        "黑哥"
                    ]
                },
                "realtion": {
                    "type": "array",
                    "description": "关系列表",
                    "items": {
                        "type": "object",
                        "required": [
                            "father",
                            "mather"
                        ],
                        "properties": {
                            "father": {
                                "type": "string",
                                "description": "父亲"
                            },
                            "mather": {
                                "type": "string",
                                "description": "母亲"
                            }
                        }
                    }
                }
            }
        }
    },
    methods: {
        open(json) {
            json && (this.schema = json);
            this.visible = true;
        },
        close(clear) {
            this.visible = false;
            clear && (this.schema = JSON.parse(JSON.stringify(this.schema2)));
        },
        settingSys(tab) {
            let name = tab.name ?? tab;
            this.schema = JsonSchema.SCHEMA_KEYS[name];
            this.$refs.table.json = new JsonSchema(this.schema);
            this.$refs.table.updateTable();
        },
        updateSchema(schema) {
            this.schema = schema;
        },
        tabInput(e) {
            e.preventDefault(); // 阻止默认事件
            const insertText = '\t'; // 插入的制表符
            const elInput = e.target;
            const startPos = elInput.selectionStart;
            const endPos = elInput.selectionEnd;

            if (startPos === undefined || endPos === undefined) return;

            const txt = elInput.value;
            elInput.value = txt.substring(0, startPos) + insertText + txt.substring(endPos);
            elInput.focus();
            elInput.selectionStart = startPos + insertText.length;
            elInput.selectionEnd = startPos + insertText.length;
            this.jsonStr = elInput.value;
        },
        writeJson() {
            if (this.validJson(this.jsonStr)) {
                this.jsonStr = JSON.stringify(this.schema, null, 4);
            }
        },
        validJson(str) {
            try {
                return JSON.parse(str);
            } catch (e) {
                return false;
            }
        },
        flushJson() {
            if (this.validJson(this.jsonStr) === false) {
                infoNotify('json格式错误，请检查');
                return;
            }
            this.schema = JSON.parse(this.jsonStr);
            this.loadFalg = false;
            setTimeout(() => {
                this.loadFalg = true
            }, 500);
        },
        onSchemaChange(v) {
            this.schema = v;
        },
        //i.el-tooltip.el-icon-setting
        findComponent(components, classname) {
            let res = [];
            components.forEach(child => {
                console.log(child.$el.className)
                if (child.$el.className === classname) {
                    res.push(child);
                }
                // console.log('cccc', child.$children, child.$children.length)
                if (child.$children.length > 0) {
                    res = res.concat(this.findComponent(child.$children, classname));
                }
            });
            return res;
        },
        load() {
            this.loadFalg = !this.loadFalg;
        },
        flush() {

        }
    },
};
</script>
<style scoped>
::v-deep(.el-button) {
    height: 22px;
    width: 60px;
    padding: 0;
    margin-right: 3px;
}

::v-deep(.el-card__body) {
    padding: 16.5px;
}

::v-deep(.json-schema-vue-editor .option-formStyle) {
    padding-top: 0;
}

::v-deep(.json-schema-vue-editor .object-style),
::v-deep(.json-schema-vue-editor .array-type) {
    padding-top: 0;
    margin-top: 0;
}

::v-deep(.el-col-8) {
    margin-top: 10px;
}

.edit {
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    overflow-y: auto;
}
</style>